package com.wyw.learning.thread.collections.concurrenthashmap;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 本身Concurrenthashmap是线程安全的，但是通过组合操作并不保证线程安全
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
public class OptionsNotSafe implements Runnable {
    private static ConcurrentHashMap<String, Integer> scores =
            new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {
        scores.put("小明", 0);
        Thread t1 = new Thread(new OptionsNotSafe());
        Thread t2 = new Thread(new OptionsNotSafe());

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(scores);

    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
//            Integer score = scores.get("小明");
//            Integer newScore = score + 1;//这样就会出现a++的线程不安全的情况,可以用syn代码块保护，但是又使用了syn，反而破坏了concurrentHashMap的精巧设计，就不如直接使用hashmap
//            scores.put("小明", newScore);


            while (true) {
                Integer score = scores.get("小明");
                Integer newScore = score + 1;
                boolean b = scores.replace("小明", score, newScore);//安全替换
                if (b) {
                    break;
                }
            }
        }

    }
}
